
const hello=new Vue({
    el:"#content",
    data:{
        list:[],
        lssuets:[],
        isShow:false,
        isTabs:false,
        countNum:0,
        countdown:3,
        tabs:[],
        data:[],
        html:'',
        info:{
            isError:false,
            message:"",
            title:'',
            css:{
                success:{'aui-message-success':false},
                error:{'aui-message-error':false},
            }
        }
    },
    mounted(){
        this.getProjects();
    },
    methods:{
        getProjects:function () {
            //'/rest/api/2/project/' + project.id + '/properties/jswSelectedBoardType';
            AP.request({
                url: '/rest/api/2/project',
                type: 'GET',
                contentType:'application/json',
                success: function(responseText){
                    let json=JSON.parse(responseText);
                    let data=[];
                    for (var i = 0; i < json.length; i++) {
                        let {avatarUrls,name,key,projectTypeKey,id}=json[i]
                        let {'16x16':img}=avatarUrls;
                        let lssuets=[];
                        data.push({img,name,key,projectTypeKey,id,lssuets,checkbox:false,type:''});
                    }
                    hello.list=data;
                    for (let i = 0; i < data.length; i++) {
                        let obj = data[i];
                        let url=`/rest/api/2/project/${obj.id}/properties/jswSelectedBoardType`;
                        typeAction(obj.id,url,1);

                    }


                },
                error: function(xhr, statusText, errorThrown){
                    console.log(arguments);
                }
            });
        },
        Action:function (id,name) {
            ///'/rest/api/2/search?jql=project='+id,
            //`/rest/agile/1.0/board/${id}/issue`

            AP.request({
                url: '/rest/api/2/search?jql=project='+id,
                type: 'GET',
                contentType:'application/json',
                success: function(responseText){
                    let json=JSON.parse(responseText);
                    let udd={};
                    if(json.total>0){
                        let data=[];
                        for (let i = 0; i < json.issues.length; i++) {
                            let {id,key,fields} = json.issues[i];
                            let {creator,summary,customfield_10020,issuetype,fixVersions,subtasks,customfield_10018,duedate}=fields;
                            let name="",log=0;
                            let sub=subtasks.length;
                            if(duedate!=null){
                                duedate=new Date(duedate);
                            }
/*                            let arr=[summary];
                            if(sub>0){
                                for (var j = 0; j < subtasks.length; j++) {
                                    let {summary:str} = subtasks[j].fields;
                                    arr.push(str);
                                }
                            }*/
                            customfield_10020=customfield_10020==null?0:customfield_10020;
                            let jsonObje={id,key,summary,customfield_10020,issuetype,name,creator,log,sub,message:'',sprint:'backlog',show:'A'}
                            if(issuetype.name=="Story"){
                                if(customfield_10018.length>0&&customfield_10018[0].indexOf("endDate")!=-1){
                                    let endTime=new Date(customfield_10018[0].substring(customfield_10018[0].indexOf("endDate="),customfield_10018[0].indexOf(",completeDate")).replace("endDate=",""));
                                    if(new Date().getTime()>endTime.getTime()||(duedate!=null&&new Date().getTime()>duedate.getTime())){
                                        jsonObje.sprint="overdue";
                                    }
                                }
                                let strs=hello.CheckString(summary);
                                jsonObje.name=strs.value;
                                jsonObje.message=strs.message;
                                data.push(jsonObje)
                            }
                        }
                        let count=0;

                        let sj = {
                            labels:['Good story','Bad story'],
                            datasets:[{data:[0,0],backgroundColor:['#14892c','#CC0033']}]
                        };
                        let point={
                            labels:['Story point(Y)','Story point(N)'],
                            datasets:[{data:[0,0],backgroundColor:['#3aa1ff','#FF6600']}]
                        }
                        for (let i = 0; i <data.length; i++) {
                            let obj = data[i];
                            if(obj.issuetype.name=="Story"){
                                getLog(obj.key,name);
                                count+=1;
                                if(obj.name=='Good story'){
                                    sj.datasets[0].data[0]++;
                                }else if(obj.name=='Bad story'){
                                    sj.datasets[0].data[1]++;
                                }
                                if(obj.customfield_10020==null||obj.customfield_10020==0){
                                    point.datasets[0].data[1]++;
                                }else if(obj.customfield_10020>0){
                                    point.datasets[0].data[0]++;
                                }
                            }

                        }
                        if(name!=null){
                            hello.lssuets.push({name:name,data:data,id:id});
                            hello.isTabs=true;
                            hello.$nextTick(function () {
                                typeAction(id,`/rest/api/2/search?jql=project=${id}%20and%20issuetype=Story%20and%20Sprint%20in%20openSprints()%20order%20by%20Rank`,3);
                                hello.DrawCircle('c1'+name,sj);
                                hello.DrawCircle('c2'+name,point);
                            });
                        }else{
                            hello.lssuets=data;
                            hello.isShow=true;
                            hello.$nextTick(function () {
                                typeAction(id,`/rest/api/2/search?jql=project=${id}%20and%20issuetype=Story%20and%20Sprint%20in%20openSprints()%20order%20by%20Rank`,2);
                                hello.DrawCircle('c1',sj);
                                hello.DrawCircle('c2',point);
                            });
                        }

                    }else{
                        if(name!=null){
                            hello.lssuets.push({name:name,data:[],message:'No data'});
                            AJS.tabs.setup();
                        }
                    }

                },
                error: function(xhr, statusText, errorThrown){
                    console.log(arguments);
                }
            });
        },
        nextHtml:function () {
            this.lssuets=[];
            this.isShow=false;
            this.isTabs=false;
            this.tabs=[];
            this.data=[];
            this.countNum=0;
            for (let i = 0; i < hello.list.length; i++) {
                let obj = hello.list[i];
                obj.checkbox=false;
            }
            $(".menu-item").empty();
            $(".tabs-pane").empty();
            $("#ppp").empty();
            $("#peri").empty();
        },
        ActionSelect:function (id) {
            for (var i = 0; i < hello.list.length; i++) {
                var obj = hello.list[i];
                if(obj.id==id&&!obj.checkbox&&hello.countNum<5){
                    obj.checkbox=true;
                    hello.countNum+=1;
                    if(hello.countNum>=5){
                        obj.checkbox=false;
                        hello.info.isError=true;
                        hello.info.message='No more than 5 options';
                        hello.info.title="Error";
                        settime();
                        hello.countNum-=1
                    }else{
                        hello.data.push({id,title:obj.name,story:0,subTask:0})
                    }
                }else if(obj.id==id&&obj.checkbox) {
                    obj.checkbox=false;
                    hello.countNum-=1;
                }
            }
        },
        CheckSelected:function () {
                    this.tabs=JSON.parse(JSON.stringify(this.data));
                      for (var j = 0; j <  hello.data.length; j++) {
                            var obj = hello.data[j];
                            //po(obj.id,'/rest/api/2/search?jql=project='+obj.id);
                          this.Action(obj.id,obj.title);
                      }
            let {title}=this.tabs[0];
            let int=setInterval(function() {
                let o=jQuery(`a[href="#${title}"]`)
                if(o!=null&&o!=''){
                    AJS.tabs.setup();
                    AJS.tabs.change(o)
                    clearInterval(int);
                }
            },1000)

        },
        CheckString(array){
            let str1   =array.replace(/\s+/g,"").toLowerCase();
            let str=array;
            let Who = new RegExp(/(as.? a?)/gmi);
            let What = new RegExp(/(I|want|like)(?:\W+\w+)?\W+(I|want|like)/gmi);
            //let What=new RegExp(/((Iwantlike)|(Iwouldlike)|(wecan))(?:\W+\w+)?\W+((Iwantlike)|(Iwouldlike)|(wecan))/gmi);
            let Why = new RegExp(/(so)(?:\W+\w+)?\W+?(so|that|)/gmi);
            //As a... I want ... so that ...
            let reg=new RegExp(/(as|a)(?:\W+\w+){1,15}?\W+(as|a|)(I|want)(?:\W+\w+){1,15}?\W+(I|want|)\b(so|that)(?:\W+\w+){1,15}?\W+(so|that|)/gmi);
            let as=str1.indexOf("asa");
            let iwant=str1.indexOf("iwant");
            let sothat=str1.indexOf("sothat");
            if(Who.exec(str).index==0&&What.test(str)&&Why.test(str)){
                    return {value:'Good story',message:''};
                }else if(!Who.test(str)&&What.test(str)&&Why.test(str)){
                    return {value:'Bad story',message:'<p>This story only has the <span class="green">What</span > and <span class="green">Why</span>. It\'s missing its <span class="red">Who</span>.</p>'};
                }else if(as==0&&!What.test(str)&&Why.test(str)){
                    return {value:'Bad story',message:'<p>This story only has the <span class="green">Who</span> and <span class="green">Why</span>. It\'s missing its <span class="red">What</span>.</p>'};
                }else if(as==0&&What.test(str)&&!Why.test(str)){
                    return {value:'Bad story',message:'<p>This story only has the <span class="green">Who</span> and <span class="green">What</span >. It\'s missing its <span class="red">Why</span>.</p>'};
                }else if(!Who.test(str)&&!What.test(str)&&Why.test(str)){
                    return {value:'Bad story',message:'<p>This story only has the <span class="green">Why</span>. It\'s missing its <span class="red">Who</span> and <span class="red">What</span>.</p>'};
                }else if(!Who.test(str)&&What.test(str)&&!Why.test(str)){
                    return {value:'Bad story',message:'<p>This story only has the <span class="green">What</span >. It\'s missing its <span class="red">Who</span> and <span class="red">Why</span>.</p>'};
                }else if(as==0&&!What.test(str)&&!Why.test(str)){
                    return {value:'Bad story',message:'This story only has the <span class="green">Who</span>. It\'s missing its <span class="red">What</span> and <span class="red">Why</span>.</p>'};
                }else{
                    return {value:'Bad story',message:'<p>This story is missing <span class="red">Who</span>, <span class="red">What</span> and Why.'};
                }
/*
            if(as==0&&iwant>0&&sothat>0&&iwant<sothat){
                return {value:'Good story',message:''};
            }else if(as<0&&iwant>0&&sothat>0&&iwant<sothat){
                return {value:'Bad story',message:'This story only has the What and Why. It\'s missing its Who.'};
            }else if(as<0&&iwant<0&&sothat<0){
                return {value:'Bad story',message:'This story is missing Who, What and Why.'};
            }else if(as==0&&iwant<0&&sothat>0){
                return {value:'Bad story',message:'This story only has the Who and Why. It\'s missing its What.'};
            }else if(as==0&&iwant>0&&sothat<0){
                return {value:'Bad story',message:'This story only has the Who and What. It\'s missing its Why.'};
            }else if(as<0&&iwant<0&&sothat>0){
                return {value:'Bad story',message:'This story only has the Why. It\'s missing its Who and What.'};
            }else if(as<0&&iwant>0&&sothat<0){
                return {value:'Bad story',message:'This story only has the What. It\'s missing its Who and Why.'};
            }else if(as==0&&iwant<0&&sothat<0){
                return {value:'Bad story',message:'This story only has the Who. It\'s missing its What and Why.'};
            }*/

        },
        DrawCircle(id,data){
            let options={
                responsive:true,
                maintainAspectRatio:false,
                onClick(v1,v2){
                        let list=[];
                        if(id=='c1'||id=="c2"||id=="c3"){
                            list=hello.lssuets;
                        }else {
                            hello.lssuets.forEach((lssue)=>{
                                if(id.indexOf(lssue.name)!=-1){
                                    list=lssue.data;
                                }
                            })
                        }
                        if(v2.length==0){
                            list.forEach((obj)=>{
                                obj.show="A";
                            })
                            return;
                        }
                        let {_view:view} = v2[0];
                            if(view.label.indexOf("Good story")!=-1){
                                list.forEach((obj)=>{
                                    obj.show="b";
                                })
                            }else if(view.label.indexOf("Bad story")!=-1){
                                list.forEach((obj)=>{
                                    obj.show="c";
                                })
                            }else if(view.label.indexOf("ongoing")!=-1){
                                list.forEach((obj)=>{
                                    obj.show="d";
                                })
                            }else if(view.label.indexOf("backlog")!=-1){
                                list.forEach((obj)=>{
                                    obj.show="e";
                                    console.log(obj.show);
                                })
                            }else if(view.label.indexOf("Story point(Y)")!=-1){
                                list.forEach((obj)=>{
                                    obj.show="f";
                                })
                            }else if(view.label.indexOf("Story point(N)")!=-1){
                                list.forEach((obj)=>{
                                    obj.show="g";
                                })
                            }else if(view.label.indexOf("overdue")!=-1){
                                list.forEach((obj)=>{
                                    obj.show="h";
                                })
                            }

                }

            }
            let my=new Chart(document.getElementById(id),
                {
                    type:"doughnut",
                    data:data,
                    options:options
                });
            my.aspectRatio = 0;
/*            new Chartist.Pie('#'+id, data, {
                labelInterpolationFnc: function(value,index) {
                    return data.series[index].name+":"+value;
                }
            });*/

        },
        open(message,type){

            if(type!='Bad story'){
                return;
            }else {
                hello.html=message;
                AJS.dialog2("#demo-dialog").show();
            }
        },Reset(){

                hello.lssuets.forEach((obj)=>{
                    if(obj.data!=null){
                        obj.data.forEach((o)=>{
                            o.show='A';
                        })
                    }else{
                        obj.show='A';
                    }

                })

        }

    }
})
var typeAction=function (id,url,type) {
    AP.request({
        url: url,
        type: 'GET',
        cache:false,
        contentType:'application/json',
        success:function(responseText){
            if(type==1){
                let type=JSON.parse(responseText).value.jswSelectedBoardType;
                for (let j = 0; j < hello.list.length; j++) {
                    let obj1 = hello.list[j];
                    if(obj1.id==id){
                        obj1.type=type;
                    }

                }
            }else if(type==2||type==3){
                let json=JSON.parse(responseText).issues;
                let point={
                    labels:['ongoing','backlog','overdue'],
                    datasets:[{data:[0,0,0],backgroundColor:['#14892c','#ccc','#FF6600']}]
                }
                let list=[];
                let Htmlid=""
                if(type==3){
                    for (let i = 0; i < hello.lssuets.length; i++) {
                        let obj = hello.lssuets[i];
                        if(obj.id==id){
                            list=obj.data
                            Htmlid='c3'+obj.name;

                        }
                    }
                }else {
                    list=hello.lssuets;
                    Htmlid="c3"
                }
                json.forEach((issue)=>{
                    let pid=issue.id;
                    for (let i = 0; i < list.length; i++) {
                        let obj = list[i];
                        if(obj.id==pid&&obj.sprint!="overdue"){
                            obj.sprint="ongoing";
                            point.datasets[0].data[0]++;
                        }
                    }
                })
                list.forEach((issue)=>{
                    if(issue.sprint=="overdue"){
                        point.datasets[0].data[2]++;
                    }
                })
                point.datasets[0].data[1]=list.length- point.datasets[0].data[0]-point.datasets[0].data[2];
                hello.DrawCircle(Htmlid,point);
            }

        },
        error: function(xhr, statusText, errorThrown){
            console.log(arguments);
        }
    });
}
    var po=function (id,url) {
        AP.request({
            url: url,
            type: 'GET',
            cache:false,
            contentType:'application/json',
            success:function(responseText){
                let json=JSON.parse(responseText).issues;
                let total=0;
                let subTask=0;
                for (let j = 0; j < json.length; j++) {
                    let obj1 = json[j];
                    if(obj1.fields.issuetype.name=='Story'){
                        total+=1;
                        subTask=subTask+obj1.fields.subtasks.length;
                    }
                }
                for (var i = 0; i < hello.tabs.length; i++) {
                    var obj =  hello.tabs[i];
                    if(obj.id==id){
                        obj.story=total;
                        obj.subTask=subTask;
                    }
                }
            },
            error: function(xhr, statusText, errorThrown){
                console.log(arguments);
            }
        });
    }
    function getLog(id,name) {
        AP.request({
            url: '/rest/api/2/issue/'+id+'/changelog',
            type: 'GET',
            cache:false,
            contentType:'application/json',
            success:function(responseText){
                let json=JSON.parse(responseText);
                let {total}=json;
                    for (let i = 0; i < hello.lssuets.length; i++) {
                        let obj=hello.lssuets[i];
                        if(name!=null){
                            for (var j = 0; j < obj.data.length; j++) {
                                var obj1 = obj.data[j];
                                if(obj1.key==id){
                                    obj.log=total;
                                }
                            }
                        }else {
                            if(obj.key==id){
                                obj.log=total;
                            }
                        }


                    }


            },
            error: function(xhr, statusText, errorThrown){
                console.log(arguments);
            }
        });
    }


function settime() {
    if (hello.countdown == 0) {
        hello.countdown = 3;
        hello.info.isError=false
        hello.info.message='';
        hello.info.title="";
    } else {
        hello.countdown--;
        setTimeout(function() {
            settime()
        },1000)
    }

}
$(document).ready(function(){

});

